const app = getApp()
const Api = require("../../utils/api.js")
const ApiRequest = require("../../utils/request.js");
const utils = require("../../utils/utils.js")

Page({
  data: {
    InputBottom: 0,
    msgInput: '',
    messageList: []
  },
   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var self = this
    let flowID = options.flowID
    let currentUser = self.getUserInfo()
    self.getMessage(flowID)
    // console.log("messageList: ", self.data.messageList)
    // console.log("currentUser: ", currentUser)
    // let messageList = [
    //   {message: '咩咩咩！', role: 'patient', name: '张三丰', 'createTime': '2018-3-23 13:20', avatarUrl: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big143004.jpg', self: true},
    //   {message: '喵喵喵！喵喵喵！喵喵喵！喵喵！喵！喵喵喵！', role: 'doctor', name: '刘秋松', 'createTime': '2018-3-23 13:23', avatarUrl: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg',  self: false}
    // ]
    //测试
    // let flowID = '7'
    this.setData({
      flowID: flowID,
      currentUser: currentUser,
    })
  },

  getUserInfo() {
    let loginUser = app.globalData.loginUser
    // console.log("loginUser: ", loginUser)
    let currentUser = {
      'id': loginUser.id,
      'realName': loginUser.realName,
      'role': ''
    }
    if(loginUser.hasOwnProperty('departmentName')) {
      currentUser.role = 'doctor'
    } else {
      currentUser.role = 'patient'
    }
    return currentUser
  },

  getMessage(flowID) {
    // console.log("flowID: ", flowID)
    var self = this
    var url = Api.get_chat + '/' + flowID;
    var params = {
    };
    var method = 'GET';
    var header = "application/json";
    var success = function (res) {
      console.log("getMessage res", res)
      if(res.code == 200) {
        let currentUser = self.data.currentUser
        let messageList = res.data
        messageList.forEach((elem, index) => {
          // console.log(elem, index);
          if(elem.personId == currentUser.id && elem.role == currentUser.role) {
            elem.self = true
          } else {
            elem.self = false
          }
          messageList[index] = elem
         });
        self.setData({
          messageList: messageList
        })
      }
    } 
    ApiRequest.request(url, params, method, header, success, self.fail);
  },

  saveMessage(message, role, personId) {
    if(role == 'doctor') {
      role = 0
    } else {
      role = 1
    }
    var self = this
    var flowID = self.data.flowID
    var url = Api.add_Chat + '/' + flowID;
    var params = {
      message: message,
      role: role,
      personId: personId
    };
    var method = 'POST';
    // var header = "application/x-www-form-urlencoded";
    var header = "application/json";
    var success = function (res) {
      console.log("saveMessage res", res)
      if(res.code == 200) {
        // self.setData({
        //   messageList: res.data
        // })
      }
    } 
    ApiRequest.request(url, params, method, header, success, self.fail);
  },

  refreshMessage(e) {
    this.getMessage(this.data.flowID)
    wx.showToast({
      title: '刷新成功',
    })
  },

  InputFocus(e) {
    // console.log("聚焦输入", e)
  },
  InputBlur(e) {
    // console.log("停止输入", e)
    this.setData({
      msgInput: e.detail.value
    })
  },

  /* 发送消息 */
  sendMessage: function (e) {
    var self = this;
    // console.log("self.data.msgInput", self.data.msgInput)
    if (self.data.msgInput == '') {
      wx.showToast({
        title: '消息内容不能为空',
        icon: 'none'
      })
      return;
    }

    var messageList = this.data.messageList;

    messageList.push({
      self: true,
      message: self.data.msgInput,
      role: self.data.currentUser.role,
      name: self.data.currentUser.realName,
      createTime: utils.formatTime(new Date())
    })

    // TODO 聊天记录存到服务器
    self.saveMessage(self.data.msgInput, self.data.currentUser.role, self.data.currentUser.id)
    // console.log("接收消息");
    this.setData({
      messageList: messageList,
      msgInput: ''
    }, function () {
      // 接收消息 (待渲染成功后)
      // console.log("渲染成功");
      // self.receiveMessage(msg, msgId);
    })
  },
})